<template>
  <div class="app-container" v-loading="loading">
    <leaseContract state="detail" v-model="form" ref="leaseContract" />
    <carReplacementService state="write" v-model="form" ref="carReplacementService" />
    <vehicleInformation state="detail" v-model="form" ref="vehicleInformation" />
    <vehicleInformationZD state="write" v-model="form" ref="vehicleInformationZD" />
    <div style="text-align: right; box-sizing: border-box; padding-right: 20px; margin-top: 20px; background-color: #fff; width: 100%; height: 60px; line-height: 60px; border-radius: 8px">
      <el-button @click="cancel">取消</el-button>
      <el-button @click="save" type="primary">保存</el-button>
      <el-button @click="submit" type="primary">确定</el-button>
    </div>
  </div>
</template>
<script>
import leaseContract from './components/leaseContract'
import carReplacementService from './components/carReplacementService'
import vehicleInformation from './components/vehicleInformation'
import vehicleInformationZD from './components/vehicleInformationZD'
import { judgmentStaging, startReplacementATicket, replacementCar } from '@/api/vehicleOrder'
export default {
  name: 'CarReplacementService',
  components: {
    leaseContract,
    carReplacementService,
    vehicleInformation,
    vehicleInformationZD,
  },
  data() {
    return {
      loading: false,
      form: {},
    }
  },
  created() {
    this.judgmentStaging()
  },
  methods: {
    async judgmentStaging() {
      let params = {
        orderId: this.$route.query.orderId,
      }
      this.loading = true
      try {
        let res = await judgmentStaging(params)
        let { data, code } = res
        if (code == 200 && data == null) {
          // 数据如果为空再调取另一个接口
          let res = await startReplacementATicket(params)
          let { data, code } = res
          if (code == 200) {
            this.data(data)
          }
        } else {
          this.data(data)
        }
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    data(data) {
      data.replacementCarType == null ? (data.replacementCarType = undefined) : data.replacementCarType
      data.driverName == null ? (data.driverName = undefined) : data.driverName
      data.replacementCarNo == null ? (data.replacementCarNo = undefined) : data.replacementCarNo
      data.replacementPublicCarNo == null || data.replacementPublicCarNo == '' ? (data.replacementPublicCarNo = '') : data.replacementPublicCarNo
      data.isDriver == null ? (data.isDriver = undefined) : data.isDriver
      data.paymentMethods == null ? (data.paymentMethods = undefined) : data.paymentMethods
      this.form = {
        ...data,
        carType: this.$route.query.carType,
        orderId: this.$route.query.IdOrder,
        calcSchemeId: this.$route.query.calcSchemeId,
        replacementPublicOrderIds: data.replacementPublicOrderIds?.split(','),
        dataDay: null,
        Hour: null,
        replacementTime: data.replacementCarStartTime == null && data.replacementCarEndTime == null ? [] : [data.replacementCarStartTime, data.replacementCarEndTime],
      }
    },
    cancel() {
      this.$tab.closeOpenPage(this.$route)
      this._toPage({
        name: 'SuborderView',
      })
    },
    dataObj(type) {
      const loading = this.$loading({
        lock: true,
        text: type == 0 ? '保存中' : '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      let data = {
        ...this.form,
        btnType: this.$route.query.btnType,
        submitState: type,
        orderCarId: this.$route.query.orderId,
        orderCarCode: this.$route.query.orderCarCode,
        replacementPublicOrderIds: this.form.replacementPublicOrderIds?.join(','),
        replacementPublicCarNo: this.form.replacementPublicCarNo,
        replacementTime: this.form.replacementTime?.join(','),
      }
      replacementCar(data)
        .then((res) => {
          if (res.code == 200) {
            loading.close()
            type == 0 ? this.$message.success('保存成功') : this.$message.success('提交成功')
            this.cancel()
          }
        })
        .catch(() => {
          loading.close()
        })
    },
    save() {
      this.dataObj(0)
    },
    async submit() {
      let result = await this.valid()
      if (result) {
        console.log(this.form.replacementPublicCarNo, 'this.form.replacementPublicCarNo')
        this.dataObj(1)
      } else {
        this.error()
      }
    },
    error() {
      this.$nextTick(() => {
        const el = document.querySelectorAll('.el-form-item__error')[0]
        el.scrollIntoView({ block: 'center', behavior: 'smooth' })
      })
    },
    valid() {
      return new Promise(async (resolve) => {
        let result = true
        let refs = Object.values(this.$refs)
        for (let index = 0; index < refs?.length; index++) {
          const ref = refs[index]
          if (Object.prototype.toString.call(ref) == '[object Array]') {
            for (let i = 0; i < ref.length; i++) {
              const element = ref[i]
              if (element?.valid) {
                let rc = await element?.valid?.()
                result = result && rc
              }
              if (element?.validate) {
                let rf = await this._valid(ref)
                result = result && rf
              }
              if (element?.form_validate) {
                let rf = await this._valid(ref, 'form_validate')
                result = result && rf
              }
            }
          } else {
            if (ref?.valid) {
              let rc = await ref?.valid?.()
              result = result && rc
            }
            if (ref?.validate) {
              let rf = await this._valid(ref)
              result = result && rf
            }
            if (ref?.form_validate) {
              let rf = await this._valid(ref, 'form_validate')
              result = result && rf
            }
          }
        }
        resolve(result)
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.app-container {
  box-sizing: border-box;
  padding-left: 30px;
}
</style>
